
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams } from 'react-router-dom'
import './index.scss'

import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useState, useEffect } from 'react'
import { createArticleApi, getArticleByIdApi, editArticleApi } from '../../apis/article'
import { useChannel } from '../../hooks/useChannel'



const { Option } = Select

const Publish = () => {
  // 获取频道列表
  const { channelList } = useChannel()
  // 提交表单
  const onFinish = (values) => {
    console.log(values)
    // 校验数据
    if (imageList.length !== type) return message.error("请上传正确数量的图片")

    const { title, content, channel_id } = values
    const reqData = {
      title,
      content,
      cover: {
        type: type,
        // 新增处理逻辑
        images: imageList.map(item => {
          if (item.response) {
            return item.response.data.url
          } else {
            return item.url
          }

        })//图片列表
      },
      channel_id
    }
    if (articleID) {
      // 编辑接口
      editArticleApi({ ...reqData, id: articleID })
    } else {
      // 新增接口 
      createArticleApi(reqData)

    }



  }

  // 上传回调
  const [imageList, setImageList] = useState([])
  const onUploadChange = (value) => {
    console.log("正在上传中");
    console.log(value);
    setImageList(value.fileList)
  }

  // 切换图片类型
  const [type, setType] = useState(1)
  const onTypeChange = (e) => {
    console.log(e.target.value);
    setType(e.target.value)
  }
  // 回填数据
  const [searchParams] = useSearchParams()
  const articleID = searchParams.get('id')
  // console.log(articleID);
  // 获取实例
  const [form] = Form.useForm()
  useEffect(() => {
    async function getArticleById() {
      const res = await getArticleByIdApi(articleID)
      form.setFieldsValue({
        ...res.data,
        type: res.data.cover.type
      });
      // 数据回填类型不一致
      // 回填图片列表
      setType(res.data.cover.type)
      // 显示图片
      setImageList(res.data.cover.images.map(url => {
        return { url }
      }))
    }
    if (articleID) {
      getArticleById()
    }

  }, [articleID, form])
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> },
            { title: `${articleID ? '编辑' : '发布'}文章` },
          ]}
          />
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {/* value属性用户选中后会将数据收集起来 */}
              {channelList.map(channel => (
                <Option key={channel.id} value={channel.id}>{channel.name}</Option>
              ))}
            </Select>
          </Form.Item>
          {/* 图片上传 */}
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={onTypeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {type > 0 &&
              <Upload
                listType="picture-card"
                showUploadList
                // 上传地址
                action={'http://geek.itheima.net/v1_0/upload'}
                name="image"
                onChange={onUploadChange}
                maxCount={type}
                fileList={imageList}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            }

          </Form.Item>
          {/* 富文本编辑器 */}
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            {/* 富文本编辑器 */}

            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                发布文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish